package com.springboot.mvc;

import com.springboot.controller.DashboardController;
import com.springboot.utils.UrlUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * On 2017/2/27 0027.
 */
//对PageController 和Dashboard 请求增加附加参数
@ControllerAdvice(basePackageClasses = {PageController.class, DashboardController.class})
public class PageResouceController {
    private final UrlPathHelper urlPathHelper;

    @Autowired
    public PageResouceController(UrlPathHelper urlPathHelper) {
        this.urlPathHelper = urlPathHelper;
    }

    /**
     * @return model中添加服务器路径
     */
    @ModelAttribute("rootPath")
    public String root(HttpServletRequest request){
        return UrlUtil.getRelativePath(urlPathHelper.getOriginatingServletPath(request));
    }

    /**
     * @return 添加model系统参数
     */
    @ModelAttribute("system")
    public Map<String,Object> system(HttpServletRequest request){
        HashMap<String, Object> system = new HashMap<>();
        SecurityContextImpl securityContextImpl = (SecurityContextImpl) request
                .getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        //获取登录用户的信息
        if (securityContextImpl!=null && securityContextImpl.getAuthentication()!=null) {
            String userName = securityContextImpl.getAuthentication().getName();
            system.put("user", userName);
            system.put("roles", securityContextImpl.getAuthentication().getAuthorities());
        }
        return system;
    }
}
